#!/usr/bin/python3
import requests
import sys

class ChatRobot():
    url = ""
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}

    def __init__(self, url):
        if len(url) == 0:
            self.url = "http://192.168.10.102:4023/webapi/entry.cgi?api=SYNO.Chat.External&method=incoming&version=2&token=%22IDZnXuzEf27bQrOXhNefQBgyGeh8ZEcjz8v3AaoVH4NSuCttqtfYdp0BWW5vQP95%22"
        else:
            self.url = url

    def send_message(self, message, fileurl):
        if len(fileurl) == 0:
            payload = "payload={\"text\": \"" + message + "\"}"
        else:
            payload = "payload={\"text\": \"" + message + "\", \"file_url\": \"" + fileurl + "\"}"
        print(self.url, self.headers, payload)
        response = requests.request("POST", self.url, headers=self.headers, data = payload)
        print("status:", response.status_code)  # 获取响应状态码
        print(response.text.encode('utf8'))

    def send_message_by_service(self, title, message, fileurl):
        totalMessage = title + "\n" + message
        self.send_message(self, totalMessage, fileurl)

def help():
    appname = sys.argv[0]
    appname = appname if appname.endswith('.py') else 'chat_robot'  # tomato is pypi package
    print('====== Chat Robot =======')
    # print(f'{appname}         # start a {WORK_MINUTES} minutes tomato clock + {BREAK_MINUTES} minutes break')
    print(f'{appname} -m      # start send a message')
    print(f'{appname} -s <n>  # start send a message by service struct')
    print(f'{appname} -h      # help')


def main():
    try:
        chatRobot = ChatRobot("http://192.168.10.102:4023/webapi/entry.cgi?api=SYNO.Chat.External&method=incoming&version=2&token=%22IDZnXuzEf27bQrOXhNefQBgyGeh8ZEcjz8v3AaoVH4NSuCttqtfYdp0BWW5vQP95%22")
        if len(sys.argv) <= 1:
            print(f'please input command by this way. Ctrl+C to exit')
            help()

        elif sys.argv[1] == '-m':
            print(f'robot ready to send a message')
            message = ""
            fileurl = ""
            if len(sys.argv) >= 3:
                message = sys.argv[2]
            if len(sys.argv) >= 4:
                fileurl = sys.argv[3]
            chatRobot.send_message(message, fileurl)
            print("send message finish: ", message)

        elif sys.argv[1] == '-s':
            print(f'robot ready to send a message by service')
            title = ""
            message = ""
            fileurl = ""
            if len(sys.argv) >= 3:
                title = sys.argv[2]
            if len(sys.argv) >= 4:
                message = sys.argv[3]
            if len(sys.argv) >= 5:
                fileurl = sys.argv[4]
            chatRobot.send_message_by_service(title, message, fileurl)
            print("send message finish: ", message)

        elif sys.argv[1] == '-h':
            help()

        else:
            help()
    except Exception:
        pass


if __name__ == "__main__":
    main()
